<?php
	define('APPID','wxd5d812281202f8b9');
	define('WXID','gh_b2aaad67636b');

	define('MCHID','1447742602');
	define('KEY','UiJ0dUiKrzMCFbeMI2AEkSmRX7BN2G7s');
	function getrandnum(){
		$yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P');
		$randn=$yCode[intval(date('Y'))-2016].strtoupper(dechex(date('m'))).date('d').substr(time(),-5).substr(microtime(),2,5).sprintf('%02d',rand(0,99));
		return $randn;
	}

	function unifiedorder($param){
		$dataurl='https://api.mch.weixin.qq.com/pay/unifiedorder';
		$set=array('appid'=>APPID,'mch_id'=>MCHID,'device_info'=>'WEB','nonce_str'=>getrandnum(),'body'=>$param['title'],'out_trade_no'=>$param['tradenumber'],'total_fee'=>$param['total']*100,'spbill_create_ip'=>$args[0]['actionIP'],'notify_url'=>'http://www.test.com/notify.wxpay.php','trade_type'=>'NATIVE','product_id'=>1);
		//echo $set['notify_url'];
		$set['sign']=sign($set);
		$text='<xml>';
		foreach($set as $key=>$value){
			$text=$text.'<'.$key.'>'.$value.'</'.$key.'>';
		}
		$text.='</xml>';
		
		$ch = curl_init();//初始化curl
		curl_setopt($ch, CURLOPT_URL,$dataurl);//抓取指定网页
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);// 1s to timeout.
		curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
		curl_setopt($ch, CURLOPT_POSTFIELDS, $text);
        	$xml = curl_exec($ch);//运行curl
		
		$xml_tree = new DOMDocument();
		$xml_tree->loadXML($xml);
		if($xml_tree->getElementsByTagName('return_code')->item(0)->nodeValue=='SUCCESS'){
			if(checksign($xml_tree)){
				if($xml_tree->getElementsByTagName('result_code')->item(0)->nodeValue=='SUCCESS'){
					$code_url=$xml_tree->getElementsByTagName('code_url')->item(0)->nodeValue;
					$data['data']['code_url']=$code_url;
				}else{
					$data['error'] = $xml_tree->getElementsByTagName('err_code')->item(0)->nodeValue.':'.$xml_tree->getElementsByTagName('err_code_des')->item(0)->nodeValue;
				}
			}else{
				$data['error'] = '错误的签名';
			}
		}else{
			$data['error'] = $xml_tree->getElementsByTagName('return_msg')->item(0)->nodeValue;
		}
		return $data;
	}

	function sign($set){
		$return='';
		ksort($set);
		foreach($set as $key=>$value){
			if(!empty($value) && $key!='sign'){
				$return.=$key.'='.$value.'&';
			}
		}
		$return.='key='.KEY;
		return strtoupper(md5($return));
	}

	function checksign($xml){
		$nodes =$xml->documentElement->childNodes;
		$set=array();
		foreach ($nodes as $elem ) {
			if($elem->nodeType==1){
				$set[$elem->nodeName]=$elem->nodeValue;
			}
		}
		if($set['sign']==sign($set)){
			return true;
		}else{
			return false;
		}
	}
	//$args[0]['amount']=0.01;
	$data=unifiedorder(array('title'=>'微信充值','tradenumber'=>$args[0]['rechargeId'],'total'=>$args[0]['amount']));
	echo $data['data']['code_url']; 